<template>
  <div class="search-content">
    <SearchHeader hide-btn>
      <SearchInput
        slot="extra"
        ref="search"
        :search-value.sync="searchText"
        v-on:clearKey="clearKey"
        v-on:cancel="handleCancelClick"
        :placeholder="'搜索'+placeholder"
        transparent
        disable-fouce
      />
    </SearchHeader>
    <div class="search-result">
      <div v-if="!isShow" class="search-condition">
        <p>搜索指定内容</p>
        <div class="search-type">
          <span
            v-for="(item, index) in tabList"
            :key="index"
            :class="activeIndex === item.id ? 'active-color' : ''"
            @tap="clickSearchArea(item.id)"
          >{{ item.text }}</span>
        </div>
      </div>
      <div v-if="isShow&&(searchData.length||owerGroup.length)" class="search-dialog">
        <ul v-if="!placeholder" class="search-title">
          <li v-for="(item, index) in tabList" :key="index" @tap="clickItem(item)">
            <span :class="activeIndex === item.id ? 'active-border' : ''">{{ item.text }}</span>
          </li>
        </ul>
        <div :class="{'person-list-top':placeholder!=''}" class="person-list">
          <div class="result-all">
            <div v-show="activeIndex !== 'tlz' && searchData.length">
              <p class="title">同事</p>
              <div
                :key="index"
                v-for="(item, index) in searchData"
                @tap="clickSearch(item, '1')"
                class="search-list"
              >
                <div v-html="item.photo" class="name-circle" />
                <p v-html="item.names" class="item-name" />
              </div>
              <div
                @tap="clickAll('sing')"
                v-show="totalData.singArr.length > 3"
                class="all-search"
              >{{ singShow ? '查看全部' : '收起' }}</div>
            </div>
            <div v-show="activeIndex !== 'ts' && owerGroup.length">
              <p class="title">群聊</p>
              <div
                :key="index"
                v-for="(item, index) in owerGroup"
                @tap="clickSearch(item, '3')"
                :class="activeIndex === item.id ? 'active' : ''"
                class="search-list"
              >
                <div class="search-title">
                  <template v-if="item.photo">
                    <img :src="item.photo" alt srcset />
                  </template>
                  <template v-else>群组</template>
                </div>
                <div class="item-name">
                  <p v-html="item.names" />
                  <!-- <div style="font-size: 12px;">
                    包含：
                    <span v-html="item.colorName" />
                  </div>-->
                </div>
              </div>
              <div
                @tap="clickAll('group')"
                v-show="totalData.groupArr.length > 3"
                class="all-search"
              >{{ groupShow ? '查看全部' : '收起' }}</div>
            </div>
          </div>
        </div>
      </div>
      <!--isShow&&searchData.length==0-->

      <div v-if="isShow" class="noData">暂无搜索内容</div>
    </div>
  </div>
</template>
<script>
import searchMatch from 'pinyin-match'
import SearchHeader from '@/components/searchHeader'
import SearchInput from '@/components/searchInput'
// import Search from '@/components/search';
import Organ from '../../class/Organ'
import Group from '../../class/Group'
import Dialog from '../../class/Dialog'
// import * as Util from '../../common/util';
import { openWindow } from '@/helper'

export default {
  name: 'SearchPage',
  components: {
    SearchHeader,
    SearchInput,
  },
  data() {
    return {
      searchText: '',
      isShow: false,
      tabList: [
        { text: '全部', id: 'qb' },
        { text: '公司同事', id: 'ts' },
        { text: '讨论组', id: 'tlz' },
      ],
      activeIndex: 'qb', // 选中的类型
      searchList: [], // 搜索单人大池子
      newGroup: [],
      allGroup: [], // 所有的组
      singShow: true, // 查看更多同事默认显示
      groupShow: true, // 查看群组默认显示
      placeholder: '',
      searchData: [],
      owerGroup: [],
      totalData: {},
    }
  },
  computed: {
    // searchList() {
    //   const list = this.
    // },
    userId() {
      return JE.getCurrentUser().id
    },
    getZhid() {
      return JE.getCurrentUser().zhId
    },
  },
  watch: {
    searchText(newVal) {
      console.log(JE.isNotEmpty(newVal))
      if (JE.isNotEmpty(newVal)) {
        this.searchText = newVal
        console.log('this.searchText', this.searchText)
        if (newVal.trim()) {
          this.isShow = true
          if (this.activeIndex && this.activeIndex != 'qb') {
            if (this.activeIndex == 'ts') {
              this.searchData = this.getOwerPerson()
              if (
                this.searchData &&
                this.searchData.length == 0 &&
                newVal.trim()
              ) {
                this.isShow = false
              }
            }
            if (this.activeIndex == 'tlz') {
              this.owerGroup = this.getOwerGroup()
              if (
                this.owerGroup &&
                this.owerGroup.length == 0 &&
                newVal.trim()
              ) {
                this.isShow = false
              }
            }
          } else {
            this.searchData = this.getOwerPerson()
            this.owerGroup = this.getOwerGroup()
            if (
              this.owerGroup.length == 0 &&
              this.searchData.length == 0 &&
              newVal.trim()
            ) {
              this.isShow = false
            }
          }
        }
      } else if (mui.os.ios) {
        console.log('ios')
        this.isShow = false
        this.searchText = ''
        this.$set(this, 'placeholder', this.setPlaceholder(this.activeIndex))
        this.singShow = true
        this.groupShow = true
      } else {
        // this.$refs.search.$refs.searchInput.blur();
        this.isShow = false
        this.searchText = ''
        this.singShow = true
        this.groupShow = true
        console.log('anzhuo')
        this.$set(this, 'placeholder', this.setPlaceholder(this.activeIndex))
        // setTimeout(() => {
        //   this.$refs.search.$refs.searchInput.focus();
        // }, 100);
      }
    },
  },
  created() {
    this.searchText = ''
  },
  async mounted() {
    this.searchText = ''
    plus.nativeUI.closeWaiting()
    // plus.webview.currentWebview().show('slide-in-right');
    this.clickItem(this.tabList[0])
    // this.getTree();
    // 获取所有的人员
    this.searchList = await Organ.fetchGetAllPeoples(this.getZhid)
    // this.getPeople();
    this.getGroupList()
    mui.later(() => {
      this.$refs.search.showSoftInput()
    }, 300)
  },
  methods: {
    getOwerPerson() {
      if (!this.isShow) {
        return false
      }
      // 如果查询的包含'.'就让为查询失败
      if (this.searchText.includes('.')) {
        this.isShow = true
        return []
      }
      const singArr = []
      console.log(this.searchList)
      this.searchList.map((item) => {
        const searchArray = searchMatch.match(item.name, this.searchText)
        if (searchArray) {
          const name = item.name.replace(
            item.name.substr(searchArray[0], this.searchText.length),
            `<span style='color:#546EFE;'>${item.name.substr(
              searchArray[0],
              this.searchText.length
            )}</span>`
          )
          this.$set(item, 'names', name)
          singArr.push(item)
        }
      })
      this.totalData.singArr = singArr
      const newArr = [...singArr]
      return newArr.splice(0, 3)
    },
    getOwerGroup() {
      if (!this.isShow) {
        return false
      }
      // 如果查询的包含'.'就让为查询失败
      if (this.searchText.includes('.')) {
        this.isShow = true
        return []
      }
      const groupArr = this.newGroup.filter((item) =>
        searchMatch.match(item.name, this.searchText)
      )
      groupArr.map((item) => {
        const searchArray = searchMatch.match(item.name, this.searchText)
        if (searchArray) {
          const name = item.name.replace(
            item.name.substr(searchArray[0], this.searchText.length),
            `<span style='color:#546EFE;'>${item.name.substr(
              searchArray[0],
              this.searchText.length
            )}</span>`
          )
          this.$set(item, 'names', name)
        }
      })
      this.totalData.groupArr = groupArr
      const newArr = [...groupArr]
      return newArr.splice(0, 3)
    },
    clickSearchArea(type) {
      this.$refs.search.$refs.searchInput.blur()
      this.activeIndex = type
      this.$set(this, 'placeholder', this.setPlaceholder(type))
      setTimeout(() => {
        this.$refs.search.$refs.searchInput.focus()
      }, 100)
    },
    setPlaceholder(type) {
      let placeholderText
      // eslint-disable-next-line default-case
      switch (type) {
        case 'ts':
          placeholderText = '公司同事'
          break
        case 'tlz':
          placeholderText = '讨论组'
          break
        case 'qb':
          placeholderText = ''
          break
      }
      return placeholderText
    },
    // 监听 清除按钮事件
    clearKey() {
      this.searchText = ''
      this.singShow = true
      this.groupShow = true
    },
    handleCancelClick() {
      mui.back(() => {
        this.searchText = ''
        this.singShow = true
        this.groupShow = true
      })
    },
    async getGroupList() {
      const list = await Group.getGroupList(this.userId)
      this.newGroup = list.map((item) => {
        const items = item.name.split('、')
        // 名字变为拼音
        const namePinyin = items.map((i) => JE.toPinYin(i, 'pinyin'))
        const namePy = items.map((i) => JE.toPinYin(i, 'py'))
        const all = namePy.concat(namePinyin, items)
        return {
          ...item,
          pinyin: namePinyin,
          py: namePy,
          chinese: items,
          all,
        }
      })
    },
    clickItem(item) {
      this.activeIndex = item.id
      setTimeout(() => {
        this.$refs.search.$refs.searchInput.focus()
      }, 100)
    },
    // 获取所有人员，按姓氏排列的所有人员
    async getPeople() {
      this.searchList = await Organ.fetchGetAllPeoples(this.getZhid)
    },
    // async getTree() {
    //   const list = await Organ.getUserInfoByUserId(this.userId);

    //   if (list.length) {
    //     // data为需要修改的tree，为点击组织树做处理
    //     this.getTreeNew(list);
    //   }
    // },
    // // 递归获取所有的人员，并且增加字段拼音,前端搜索数据来源
    // getTreeNew(treeList) {
    //   treeList.map((item) => {
    //     if (item.children.length) {
    //       this.allGroup.push(item);
    //       this.getTreeNew(item.children);
    //     } else {
    //       if (item.type && item.type === '1') {
    //         this.$set(item, 'photo', JE.getUserPhoto(item.id, true));
    //         this.searchList.push(item);
    //       }
    //       return this.searchList;
    //     }
    //   });
    // },
    // 鼠标点击事件
    clickSearch(item, type) {
      console.log('搜索--------')
      openWindow({
        url: 'pages_userinfo_index.html',
        id: 'userinfo',
        title: '个人信息',
        extras: {
          userId: item.id,
        },
      })
      // const inputElement = this.$el.querySelector('input')
      // inputElement.blur()
      // if (type === '1') {
      //   if (this.userId === item.id) {
      //     JE.msg('自己不能和自己聊天哈~')
      //     this.searchText = ''
      //     return false
      //   }
      //   const res = await Dialog.createSingleChat(
      //     JE.getCurrentUser().id,
      //     item.id,
      //     item
      //   )
      //   const ws = plus.webview.currentWebview()
      //   plus.webview.close(ws)
      //   this.$nextTick(() => {
      //     const targetWebview = plus.webview.getWebviewById('JE-PLUGIN-IM')
      //     res.title = item.name
      //     mui.fire(targetWebview, 'createdSing', res)
      //     this.searchText = ''
      //   })
      // } else if (type === '3') {
      //   if (item.id) {
      //     const resObj = await Dialog.createGroupChat(
      //       item.id,
      //       JE.getCurrentUser().id,
      //       item
      //     )
      //     const ws = plus.webview.currentWebview()
      //     plus.webview.close(ws)
      //     this.$nextTick(() => {
      //       const targetWebview = plus.webview.getWebviewById('JE-PLUGIN-IM')
      //       mui.fire(targetWebview, 'createdGroup', resObj)
      //       resObj.title = `群对话(${item.name.split('、').length})`
      //       this.searchText = ''
      //     })
      //   }
      // }
      // this.isShow = false
    },
    // 点击查看全部
    clickAll(type) {
      if (type === 'sing') {
        setTimeout(() => {
          const newArr = [...this.totalData.singArr]
          if (!this.singShow) {
            this.searchData = newArr.splice(0, 3)
          } else {
            this.searchData = newArr
          }
          // 键盘不收起
          this.$refs.search.$refs.searchInput.blur()
          this.singShow = !this.singShow
        }, 200)
      } else if (type === 'group') {
        setTimeout(() => {
          const newArr = [...this.totalData.groupArr]
          if (!this.groupShow) {
            this.owerGroup = newArr.splice(0, 3)
          } else {
            this.owerGroup = newArr
          }
          // 键盘不收起
          this.$refs.search.$refs.searchInput.blur()
          this.groupShow = !this.groupShow
        }, 200)
      }
    },
  },
}
</script>
<style>
img {
  width: 80px !important;
  height: 80px !important;
  border-radius: 50%;
}
.noData {
  color: #666;
  text-align: center;
  line-height: 80px;
  font-size: 28px;
}
</style>

<style lang="less" scoped>
.search-content {
  width: 100%;
  height: 100%;
  position: relative;
  background: #f8f8f8;
  overflow: hidden;
  .search-result {
    position: absolute;
    top: 90px;
    bottom: 0;
    left: 5px;
    right: 5px;
    background: #fff;
    z-index: 1000;
    .search-condition {
      text-align: center;
      p {
        font-size: 28px;
        font-weight: 400;
        color: rgba(169, 171, 169, 1);
        line-height: 40px;
        text-align: center;
        padding-top: 60px;
        padding-bottom: 40px;
      }
      .search-type {
        font-weight: 400;
        color: rgba(83, 109, 254, 1);
        line-height: 34px;
        span {
          font-size: 24px;
          display: inline-block;
        }
        span:first-child {
          margin-right: 40px;
        }
        span:last-child {
          margin-left: 40px;
        }
        .active-color {
          color: rgba(169, 171, 169, 1);
        }
      }
    }
    .search-dialog {
      width: 100%;
      height: 100%;
      overflow: hidden;
      position: relative;
      .search-title {
        width: 100%;
        overflow-x: scroll;
        border-bottom: 1px solid #f5f5f5;
        li {
          display: inline-block;
          width: 33%;
          text-align: center;
          height: 100px;
          span {
            font-size: 32px;
            font-weight: 400;
            color: rgba(63, 63, 63, 1);
            display: inline-block;
            line-height: 96px;
          }
          .active-border {
            border-bottom: 2px solid #536dfe;
          }
        }
      }
      .title {
        width: 100%;
        padding: 20px 34px 0px 5px;
        font-size: 28px;
        font-weight: 500;
        color: rgba(190, 190, 190, 1);
        line-height: 40px;
        border-bottom: 1px solid #ededed;
      }
      .all-search {
        width: 100%;
        height: 40px;
        font-size: 28px;
        font-weight: 500;
        color: rgba(84, 110, 254, 1);
        line-height: 40px;
        padding-left: 17px;
      }
      .person-list {
        overflow: hidden;
        width: 100%;
        position: absolute;
        top: 102px;
        bottom: 0;
        border-bottom: 1px solid #fff;
        .result-all {
          width: 100%;
          height: 100%;
          overflow-y: scroll;
          overflow-x: hidden;
        }
      }
      .person-list-top {
        top: 0 !important;
      }
      .search-list {
        display: flex;
        align-items: center;
        padding: 15px 17px;
        img {
          width: 80px;
          height: 80px;
          border-radius: 50%;
        }
        .name-circle,
        .search-title {
          width: 80px;
          height: 80px;
          display: block;
          background: rgba(252, 179, 63, 1);
          border-radius: 50%;
          text-align: center;
          line-height: 80px;
          font-size: 28px;
          color: #fff;
          img {
            width: 80px !important;
            height: 80px !important;
            border-radius: 50%;
          }
        }
        .search-title {
          background: #536dfe !important;
          overflow: hidden;
        }
        .item-name {
          color: #333333;
          font-size: 28px;
          overflow: hidden;
          white-space: nowrap;
          width: 85%;
          text-overflow: ellipsis;
          padding-left: 10px;
          p {
            width: 100%;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }
        }
        .item-souce {
          color: #919090;
          font-size: 24px;
        }
      }
    }
  }
}
</style>
